﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.BL;
using OBUCare.Core.Common;
using System.Data.SqlClient;

namespace OBUCare.Web.Controllers
{
    /// <summary>
    /// 处理交易流水
    /// </summary>
    public class TransactionController : Controller
    {
        private OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        UserMgr uMgr = new UserMgr();
        ConfigMgr configMgr = new ConfigMgr();

        static string orderUser = "";
        //
        // GET: /Transaction/

        public ActionResult Index(long? id, string orderUserNo, long? SERIAL_ID, string Log_ID)
        {
            orderUser = "";
            ViewBag.ID = id.HasValue ? id : -1;
            if (orderUserNo != "" && orderUserNo != null)
                orderUser = orderUserNo;

            ViewBag.SERIAL_ID = SERIAL_ID;
            ViewBag.Log_ID = Log_ID;

            return View();
        }
        /// <summary>
        /// 主菜单默认界面为空白
        /// </summary>
        /// <returns></returns>
        public ActionResult ParentPage()
        {
            return View();
        }

        /// <summary>
        /// 用于ajax访问，并返回数据的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult List(long? id, string searchSql, string AgentNo)
        {
            try
            {
                //如果是本营业厅的权限 则只显示本营业厅业务操作记录的信息 反则显示所有
                string whereAgentNo = AgentNo == null || AgentNo == "" ? "" : " AND postInfo.AGENT_NO='" + AgentNo + "'";
                //未生成流水的交易
                IEnumerable<TransactionLogViewModel> transactions = null;
                if (orderUser != "")
                {
                    string specialContent = searchSql == null || searchSql == "" ? " AND prints.ID IS NULL " : "";
                    string CurrentDay = " AND RECORD_TIME>='" + DateTime.Now.ToShortDateString() + "'" + " AND RECORD_TIME<'" + DateTime.Now.AddDays(1).ToShortDateString() + "' ";
                    transactions = getTransLogs(" AND L.USER_NO='" + orderUser + "'" + whereAgentNo + specialContent + CurrentDay);
                }
                else
                {
                    string specialCondtion = searchSql == null || searchSql == "" ? " AND RECORD_TIME>='" + DateTime.Now.ToShortDateString() + "'" + " AND RECORD_TIME<'" + DateTime.Now.AddDays(1).ToShortDateString() + "' "
                        + " AND prints.ID IS NULL " : "";
                    transactions = getTransLogs(searchSql + whereAgentNo + specialCondtion);
                }
                var model = toTransactionViewModel(transactions);
                var temp = new GridModel(transactions);
                orderUser = "";
                return View(temp);
                ////未生成流水的交易
                //IEnumerable<OPERATION_CARE_LOGS> transactions = null;

                //if (id.HasValue && id.Value > 0)
                //{
                //    var t = obuMgr.GetOperationLogs(id.Value);
                //    transactions = new List<OPERATION_CARE_LOGS>() { t };
                //}
                //else
                //{
                //    if (orderUser != "")
                //        transactions = obuMgr.GetOperationLogs(false, " AND USER_NO='" + orderUser + "'");
                //    else if (searchSql != null)
                //    {
                //        transactions = obuMgr.GetOperationLogs(false, searchSql);
                //    }
                //    else
                //    {
                //        transactions = obuMgr.GetOperationLogs(false);
                //    }
                //}

                //var model = toTransactionLogViewModel(transactions);
                //var temp = new GridModel(model);
                //return View(temp);
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                throw ex;
            }

        }


        [HttpPost]
        public ActionResult Search(string txtTransferNo, string txtObuNo, string txtUserNo)
        {
            try
            {
                string sql = "";
                if (txtTransferNo != "")
                    sql = " AND prints.SERIAL_NO='" + txtTransferNo + "'";
                if (txtObuNo != "")
                    sql += " and obu_no ='" + txtObuNo + "'";
                if (txtUserNo != "")
                    sql += " AND L.USER_NO='" + txtUserNo + "'";
                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        [HttpGet]
        public ActionResult GetFundTypes()
        {
            try
            {
                var fundTypes = configMgr.GetTypeValues(ConfigMgr.tblFundType);
                List<string> list = new List<string>();
                fundTypes.Each(f =>
                {
                    if (!string.IsNullOrEmpty(f.DICT_CODE))
                    {
                        list.Add(f.DICT_CODE);
                    }
                });
                var data = new { Types = list };
                System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                return Content(jss.Serialize(data));
            }
            catch (Exception ex)
            {
                return Content("false");
            }
        }

        [HttpGet]
        public ActionResult GetAllAmount(string serialID)
        {
            long serialId = long.Parse(serialID);
            //根据流水单id查询该流水单下所有的资金来源金额之和与当前用户选择的金额来源总和对比，如果不一致就给予提示，一致就放行
            string sql = "SELECT SUM(AMOUNT) FROM FUND_INFO AS A INNER JOIN FUND_DETAIL AS B ON A.ID=B.FUND_ID AND B.SERIAL_ID=@SERIAL_ID";
            SqlParameter parameter = new SqlParameter("@SERIAL_ID", SqlDbType.BigInt);
            parameter.Value = serialId;
            //数据库中所有该流水单涉及到的所有来源金额之和
            decimal allAmount = db.Database.SqlQuery<decimal>(sql, parameter).FirstOrDefault();
            return Content("" + allAmount);
        }


        [HttpPost]
        public ActionResult InsertConfirmed()
        {
            //如果以参数的形式传过来，则只能取到最后一个值
            string checkedRecords = Request.Form["checkedRecords"];
            string serialNos = Request.Form["serialNos"];
            string strUserNo = "";
            var u = UIUtility.GetCurrentUser();

            //检查该号在数据库中是否已经存在。

            if (checkedRecords != null)
            {
                //如果流水单号的ID不为空，则更新该流水单的资金来源信息
                if (serialNos != "")
                {
                    long serialID = long.Parse(serialNos);

                    //根据流水单ID获取资金来源详细信息
                    IEnumerable<FUND_DETAIL> fundDetail = (from i in db.FUND_DETAIL
                                                           where i.SERIAL_ID == serialID
                                                           select i).ToList();
                    fundDetail.Each(fund =>
                        {
                            //根据资金来源详细信息的ID获取资金来源的映射关系
                            var fundinfo = db.FUND_INFO.Find(fund.FUND_ID);
                            db.FUND_INFO.Remove(fundinfo);//删除资金来源信息
                            db.FUND_DETAIL.Remove(fund);//删除资金来源详细信息
                        });

                    //根据流水单ID获取流水日志信息
                    PRINT_LOG printLog = db.PRINT_LOG.Find(serialID);
                    //更新日志信息
                    printLog.AGENT_NO = u.AgentNo;
                    printLog.CLIENT_IP = u.CLIENT_IP;
                    printLog.CREATED_DATE = DateTime.Now;
                    //// 根据流水单ID获取流水详细信息
                    //IEnumerable<PRINT_DETAIL> printDetails = (from i in db.PRINT_DETAIL
                    //                                          where i.SERIAL_ID == serialID
                    //                                          select i).ToList();
                    //printDetails.Each(printDetail =>
                    //    {
                    //        var detail = db.PRINT_DETAIL.Find(printDetail.ID);//删除流水单详细表中映射信息
                    //        db.PRINT_DETAIL.Remove(detail);
                    //    });

                    //db.PRINT_LOG.Remove(printLog);//删除历史的生成流水单信息
                    var Ids = checkedRecords.Split(',');
                    IList<long> logIdAll = new List<long>();
                    OPERATION_CARE_LOGS logInfo = null;
                    if (Ids.Length > 0)
                    {
                        //IList<IList<FUND_INFO>> fundall = new List<IList<FUND_INFO>>();
                        foreach (var id in Ids)
                        {
                            logInfo = obuMgr.GetOperationLogs(id.ToLong().Value);
                            logIdAll.Add(logInfo.ID);
                        }
                        IList<FUND_INFO> funds = getFundInfos(logInfo, u);
                        strUserNo = logInfo.USER_NO;

                        funds.Each
                            (
                               f =>
                               {
                                   db.FUND_INFO.Add(f);
                                   db.SaveChanges(); //生成资金来源ID
                                   FUND_DETAIL fd = new FUND_DETAIL();
                                   fd.SERIAL_ID = printLog.ID;
                                   fd.FUND_ID = f.ID;
                                   db.FUND_DETAIL.Add(fd);
                               }
                           );

                        db.SaveChanges();
                    }
                    string urli = "/Transaction/Index/?orderUserNo=" + strUserNo + "&SERIAL_ID=" + printLog.ID + "&Log_ID=" + checkedRecords;
                    return Content("<Script>  window.location.href = '" + urli + "';</Script>");
                }
                else
                {

                    var ids = checkedRecords.Split(',');
                    IList<long> logIds = new List<long>();
                    OPERATION_CARE_LOGS log = null;
                    if (ids.Length > 0)
                    {
                        //IList<IList<FUND_INFO>> fundall = new List<IList<FUND_INFO>>();
                        foreach (var id in ids)
                        {
                            log = obuMgr.GetOperationLogs(id.ToLong().Value);
                            logIds.Add(log.ID);
                            if (!string.IsNullOrEmpty(obuMgr.IsAlreadySerial(log.ID)))
                            {
                                return Content("<Script>alert('该日志的流水单号已生成，请查询日报明细报表或刷新页面！'); window.location.href='/Transaction/Index/';</Script>");
                            }
                        }
                        IList<FUND_INFO> funds = getFundInfos(log, u);

                        strUserNo = log.USER_NO;
                        var plog = obuMgr.NewTransactionSerial(logIds, log.USER_NO, u, funds);

                        string urli = "/Transaction/Index/?orderUserNo=" + strUserNo + "&SERIAL_ID=" + plog.ID + "&Log_ID=" + checkedRecords;
                        return Content("<Script>  window.location.href = '" + urli + "';</Script>");
                        //return View("Index", new { orderUserNo = strUserNo, SERIAL_ID = plog.ID, Log_ID = checkedRecords });
                        //return RedirectToRoute("/Transaction/Index/", new { orderUserNo = strUserNo, SERIAL_ID = plog.ID, Log_ID = checkedRecords });
                        //return RedirectToAction("Index", new { orderUserNo = strUserNo, SERIAL_ID = plog.ID, Log_ID = checkedRecords });
                    }
                }
            }
            string url = "/Transaction/Index/?orderUserNo=" + strUserNo;
            return Content("<Script>  window.location.href = '" + url + "';</Script>");
        }


        private IList<FUND_INFO> getFundInfos(OPERATION_CARE_LOGS log, OPERATOR u)
        {
            List<FUND_INFO> list = new List<FUND_INFO>();

            //var agent=uMgr.GetAgentInfo(log.POS_ID);

            var fundTypes = configMgr.GetTypeValues(ConfigMgr.tblFundType);

            fundTypes.Each(f =>
                {
                    var form = Request.Form;
                    string dictCode = f.DICT_CODE;
                    decimal? amount = form.GetValueByName("AMOUNT" + dictCode).Todecimal();
                    if (amount.HasValue)
                    {
                        FUND_INFO info = new FUND_INFO();
                        info.AMOUNT = amount.Value;
                        info.AGENT_NO = u.AgentNo;
                        info.CHEQUE_EXPIRE_TIME = form.GetValueByName("CHEQUE_EXPIRE_TIME" + dictCode).ToDateTime();
                        info.FUND_FROM = form.GetValueByName("FUND_FROM" + dictCode).ToInt().Value;
                        info.FUND_NO = form.GetValueByName("FUND_NO" + dictCode).ToText();
                        info.FUND_TIME = DateTime.Now;
                        info.OPERATOR_NO = u.OPERATOR_NO;
                        info.REMARK = form.GetValueByName("REMARK" + dictCode).ToText();
                        info.STATUS = 1;
                        info.USER_NO = log.USER_NO;

                        //添加前检查是否有可以合并的项
                        var existItem = list.FirstOrDefault(i => i.FUND_FROM.Equals(info.FUND_FROM));
                        if (existItem != null)
                        {
                            existItem.AMOUNT += info.AMOUNT;
                            if (existItem.CHEQUE_EXPIRE_TIME == null)
                                existItem.CHEQUE_EXPIRE_TIME = info.CHEQUE_EXPIRE_TIME;
                            if (existItem.FUND_NO.IsNullOrEmpty())
                                existItem.FUND_NO = info.FUND_NO;

                            existItem.REMARK += info.REMARK;
                        }
                        else
                            list.Add(info);
                    }
                });


            return list;
        }

        protected string getSqlSelect(string checkCondtion)
        {
            string sqlSelect = "SELECT L.ID AS ID, L.ID TransactionLogID,L.operation_id OperationID, prints.ID SERIAL_ID,prints.SERIAL_NO, L.USER_NO,l.OBU_NO, "
                        + " USERINFO.[USER_NAME] User_name,operationType.DICT_TITLE AS TransactionType,l.OPERATION_KIND,"
                        + " USERINFO.[USER_NAME] User_name,operationType.DICT_CODE AS TransactionTypeID,operationType.DICT_TITLE AS TransactionType,"
                        + " L.AMOUNT RepairPrice, L.RECORD_TIME CREATED_DATE,"
                        + " l.remark REMARK,"
                        + " L.OPERATOR_NO AS Operator,OPERATORS.OPERATOR_NAME AS OperatorName ,"
                        + " Agents.AGENT_NO Agent,Agents.AGENT_NAME AgentName FROM (SELECT * FROM [OPERATION_CARE_LOGS] WHERE STATUS=1 ) AS l  "

                       // + "left outer join PRINT_DETAIL p on p.LOG_ID=l.ID "

                       //+ " LEFT OUTER JOIN PRINT_LOG AS LOGS ON LOGS.ID=P.serial_id AND LOGS.STATUS=1 "
                       +" left join (select a.LOG_ID,b.ID,b.SERIAL_NO from PRINT_DETAIL as a inner join PRINT_LOG as b on a.SERIAL_ID=b.id and b.STATUS=1) as prints on l.id=prints.LOG_ID "
                        + checkCondtion

                        + "LEFT OUTER JOIN   ISSUE_RPT.dbo.CUSTOMERS AS USERINFO ON l.USER_NO = USERINFO.USER_NO  "
                        + "LEFT OUTER JOIN   ISSUE_RPT.dbo.TABLE_POSINFO AS postInfo ON L.POS_ID = postInfo.ID "
                        + "LEFT OUTER JOIN   ISSUE_RPT.dbo.OPERATORS AS OPERATORS ON OPERATORS.OPERATOR_NO = L.OPERATOR_NO "
                        + "LEFT OUTER JOIN   ISSUE_RPT.dbo.ISSUER_AGENTS AS Agents ON Agents.AGENT_NO = postInfo.AGENT_NO  "
                        + "LEFT OUTER JOIN   "
                        + "(SELECT     ID, DICT_TYPE_ID, DICT_TITLE, DICT_INDEX, DICT_CODE, REMARK, STATUS, CREATED_BY, "
                        + "CREATED_DATE, MODIFY_BY, MODIFY_DATE                            FROM          dbo.DICT_TYPE_VALUE   "
                        + "WHERE      (DICT_TYPE_ID IN "
                        + "(SELECT     ID   "
                        + "FROM          dbo.DICT_TYPE  "
                        + "WHERE      (TYPE_CODE = 'TransactionType')))) AS operationType ON L.OPERATION_KIND = operationType.DICT_CODE  where l.STATUS=1";

            return sqlSelect;
        }
        public IEnumerable<TransactionLogViewModel> getTransLogs(string sqlWhere)
        {
            try
            {
                string checkCondtion = sqlWhere == "" ? "  LEFT OUTER JOIN PRINT_LIST AS LIST ON P.serial_id =LIST.SERIAL_ID " : "";

                string sqlSelect = getSqlSelect(checkCondtion);
                //Convert0 ServicePrice ,0 ReturnPrice,0 OtherPrice,0 SumPrice ,
                //默认显示未打印的
                string normalCondtion = " AND LIST.ID  is  null ";
                //如果查询条件为空 则未打印条件有效 如果不为空 则未打印条件失效
                string condtion = sqlWhere.Trim() == "" ? normalCondtion : sqlWhere;
                string sql = sqlSelect
                    + " AND  ((l.OPERATION_KIND!=" + TransactionType.ReturnDeposit.ToInt() + " AND l.AMOUNT>0 ) "
                      + " OR (L.OPERATION_KIND=" + TransactionType.ReturnDeposit.ToInt() + ")) " + condtion  // AND L.OPERATION_KIND!=3004 
                    + " order by l.[RECORD_TIME] desc";

                return db.Database.SqlQuery<TransactionLogViewModel>(sql);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private IEnumerable<TransactionLogViewModel> getTransLogsBySERIAL_ID(long id, string logsID)
        {
            try
            {
                //string sqlSelect = getSqlSelect("  LEFT OUTER JOIN PRINT_LIST AS LIST ON P.serial_id =LIST.SERIAL_ID ");
                string sqlSelect = getSqlSelect(" ");
                string strLogsID = logsID == "" ? "" : " AND L.ID IN (" + logsID + ")";
                string sql = sqlSelect
                    + string.Format(" AND  ((l.OPERATION_KIND!=" + TransactionType.ReturnDeposit.ToInt() + " AND l.AMOUNT>0 ) "
                + " OR (L.OPERATION_KIND=" + TransactionType.ReturnDeposit.ToInt() + "))"
                + " AND prints.ID ={0} {1} ", id, strLogsID)
                    + " order by l.[RECORD_TIME] desc";

                return db.Database.SqlQuery<TransactionLogViewModel>(sql);


            }
            catch (Exception)
            {

                throw;
            }
        }

        private IEnumerable<TransactionLogViewModel> toTransactionViewModel(IEnumerable<TransactionLogViewModel> logs)
        {
            try
            {
                var r = from log in logs
                        select toTransactionModel(log);

                return r.ToList();

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private TransactionLogViewModel toTransactionModel(TransactionLogViewModel log)
        {
            TransactionLogViewModel m = new TransactionLogViewModel();

            m.CREATED_DATE = log.CREATED_DATE;
            m.ID = log.ID;
            m.TransactionLogID = log.ID;
            m.OperationID = log.OperationID;
            m.SERIAL_ID = log.SERIAL_ID;
            m.SERIAL_NO = log.SERIAL_NO;
            m.TransactionType = log.TransactionType;
            m.USER_NO = log.USER_NO;
            m.User_name = log.User_name;
            m.Agent = log.Agent;
            m.AgentName = log.AgentName;
            m.Operator = log.Operator;
            m.OperatorName = log.OperatorName;
            m.ReturnPrice = Convert.ToDecimal("0"); //todo:处理金额
            m.RepairPrice = Convert.ToDecimal(log.RepairPrice);
            m.OtherPrice = Convert.ToDecimal("0");
            m.SumPrice = Convert.ToDecimal("0");
            m.ServicePrice = Convert.ToDecimal("0");
            m.REMARK = log.REMARK;


            return m;
        }


        //private IEnumerable<TransactionLogViewModel> toTransactionLogViewModel(IEnumerable<OPERATION_CARE_LOGS> logs)
        //{
        //    var r = from log in logs
        //            select toTransactionLogViewModel(log);

        //    return r.ToList();
        //}



        //private TransactionLogViewModel toTransactionLogViewModel(OPERATION_CARE_LOGS log)
        //{
        //    TransactionLogViewModel m = new TransactionLogViewModel();
        //    m.CREATED_DATE = log.RECORD_TIME;
        //    m.ID = log.ID;
        //    m.TransactionLogID = log.ID;
        //    m.TransactionType = configMgr.GetTypeValue(ConfigMgr.tblTransactionType, log.OPERATION_KIND.ToText()).DICT_TITLE;

        //    var baseInfo = obuMgr.GetObuInfo(log.OBU_NO);
        //    if (baseInfo != null)
        //    {
        //        m.User_name = baseInfo.USER_NAME;
        //        m.USER_NO = baseInfo.USER_NO;
        //    }
        //    m.SERIAL_NO = null;
        //    m.SERIAL_ID = null;


        //    m.ReturnPrice = 0; //todo:处理金额
        //    m.RepairPrice = log.AMOUNT;
        //    m.OtherPrice = 0;
        //    m.REMARK = log.REMARK;
        //    m.OtherPrice = 0;

        //    return m;
        //}

        #region 流水打印

        public ActionResult Print(long SERIAL_ID, string Log_ID)
        {
            string exportFileTitle = "流水单.xls";
            ActionResult result = Content("");
            try
            {
                string template = null;
                //ExportHelper export = null;
                var u = UIUtility.GetCurrentUser();


                //int sheetIndex = 0;

                string logsID = Log_ID;
                if (logsID.EndsWith(","))
                    logsID = logsID.Substring(0, logsID.Length - 1);

                var logs = getTransLogsBySERIAL_ID(SERIAL_ID, logsID).ToList();

                var log = logs.First();

                #region 获取资金来源

                var fundIDs = (from d in db.FUND_DETAIL
                               where d.SERIAL_ID.Equals(SERIAL_ID)
                               select d.FUND_ID).ToList();
                var fundInfos = (from f in db.FUND_INFO
                                 where fundIDs.Contains(f.ID)
                                 orderby f.FUND_FROM ascending
                                 select f).ToList();

                var fundFrom = configMgr.GetTypeValues(ConfigMgr.tblFundType);

                #endregion

                #region 处理打印历史记录

                PRINT_LIST pList = new PRINT_LIST();
                pList.AGENT_NO = u.AgentNo;
                pList.OPERATOR_NO = u.OPERATOR_NO;
                pList.PRINT_TIME = DateTime.Now;
                pList.REMARK = "";
                pList.SERIAL_ID = SERIAL_ID;
                pList.USER_NO = log.USER_NO;

                db.PRINT_LIST.Add(pList);
                db.SaveChanges();

                //打印字数
                int printCount = (from p in db.PRINT_LIST
                                  where p.SERIAL_ID == SERIAL_ID
                                  select p).Count();

                #endregion

                var repairOrder = db.REPAIR_ORDERS.Find(log.OperationID);
                string repairOrderNo = "";
                if (repairOrder != null)
                    repairOrderNo = repairOrder.REPAIR_ORDER_NO; //维修单号
                ViewBag.RepairOrderNo = repairOrderNo;
                ViewBag.PrintCount = printCount;

                //如果是单独收取押金
                if (logs.All(l => l.TransactionTypeID == TransactionType.CollectsDeposit.ToInt().ToText()))
                {

                    #region 单独收取押金




                    //template = this.GetTemplateFilePath("流水单收押金.xls");
                    //export = new ExportHelper(template);

                    ////将合计行往后移动数据总行数一1,同时输出营业厅和打印日期
                    //export.ExportAddionalInfomation((excel, ep) =>
                    //{
                    //    excel.ActiveSheetIndex = sheetIndex;

                    //    var repairOrder = db.REPAIR_ORDERS.Find(log.OperationID);

                    //    //营业厅
                    //    excel[1, 1] = log.AgentName;
                    //    excel[1, 3] = log.CREATED_DATE.ToString(UIConstants.DateFormatString); //交易日期
                    //    excel[1, 5] = log.SERIAL_NO;//流水编号
                    //    excel[1, 6] = string.Format("打印次数：{0}", printCount);//打印次数

                    //    excel[2, 1] = log.User_name;//客户名称
                    //    excel[2, 5] = log.USER_NO;//客户编号
                    //    excel[3, 1] = log.OBU_NO;//标签号
                    //    if (repairOrder != null)
                    //        excel[3, 5] = repairOrder.REPAIR_ORDER_NO;//维修单号

                    //    excel[7, 1] = DateTime.Now.ToString(UIConstants.DateFormatString);//打印时间
                    //    excel[7, 4] = log.OperatorName; //操作员


                    //    //处理资金来源的金额部分
                    //    fundInfos.Each(f =>
                    //    {
                    //        excel[5, f.FUND_FROM] = fundFrom.FirstOrDefault(t => t.DICT_CODE.Equals(f.FUND_FROM.ToString())).DICT_TITLE + "(元)";
                    //        excel.SetCellValue(6, f.FUND_FROM, f.AMOUNT);
                    //    });                    
                    ViewBag.FundInfos = fundInfos;
                    //    //写入合计
                    //    decimal sumAmount = fundInfos.Sum(f => f.AMOUNT);
                    //    excel.SetCellValue(6, 6, sumAmount);

                    //处理交易类型
                    ViewBag.RepairPrice = logs.Sum(l => l.RepairPrice);
                    //    excel.SetCellValue(4, 1, logs.Sum(l => l.RepairPrice));
                    //    //int index = 0;
                    //    //var lg = logs.GroupBy(l => l.TransactionType).ToList();
                    //    //lg.Each(g =>
                    //    //{
                    //    //    excel[4 + index, 0] = g.Key + "：";
                    //    //    excel.SetCellValue(4 + index, 1, g.Sum(l => l.RepairPrice));
                    //    //    index++;
                    //    //});

                    //    //将交易类型以下的行向上移动
                    //    //excel.ShiftRows(9,17,-(5-lg.Count()));
                    //    //excel.ShiftRows(7, 15, -(3 - lg.Count()));
                    //});
                    result = View("PrintTransInDeposit", log);
                    #endregion
                }
                else
                {

                    #region 非单独收取押金

                    /*template = this.GetTemplateFilePath("流水单退押金_收款.xls");
                    export = new ExportHelper(template);

                    //将合计行往后移动数据总行数一1,同时输出营业厅和打印日期
                    export.ExportAddionalInfomation((excel, ep) =>
                    {
                        excel.ActiveSheetIndex = sheetIndex;

                        var repairOrder = db.REPAIR_ORDERS.Find(log.OperationID);

                        //营业厅
                        excel[1, 1] = log.AgentName;
                        excel[1, 3] = log.CREATED_DATE.ToString(UIConstants.DateFormatString); //交易日期
                        excel[1, 5] = log.SERIAL_NO;//流水编号
                        excel[1, 6] = string.Format("打印次数：{0}", printCount);//打印次数

                        excel[2, 1] = log.User_name;//客户名称
                        excel[2, 5] = log.USER_NO;//客户编号
                        excel[3, 1] = log.OBU_NO;//标签号
                        if (repairOrder != null)
                            excel[3, 5] = repairOrder.REPAIR_ORDER_NO;//维修单号

                        excel[9, 1] = DateTime.Now.ToString(UIConstants.DateFormatString);//打印时间
                        excel[9, 4] = log.OperatorName; //操作员


                        //处理资金来源的金额部分
                        //fundInfos.Each(f =>
                        //{
                        //    excel[5, f.FUND_FROM] = fundFrom.FirstOrDefault(t => t.DICT_CODE.Equals(f.FUND_FROM.ToString())).DICT_TITLE + "(元)";
                        //    excel.SetCellValue(6, f.FUND_FROM, f.AMOUNT);
                        //});
                        //写入合计
                        //decimal sumAmount = fundInfos.Sum(f => f.AMOUNT);
                        //excel.SetCellValue(6, 6, sumAmount);

                        //维修费
                        decimal? repariFee = 0;
                        var tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.RepairObu.ToInt().ToText());
                        repariFee = tempLogs.Sum(l => l.RepairPrice);
                        excel.SetCellValue(4, 1, repariFee);


                        //服务费
                        decimal? serviceFee = 0;
                        tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.RepairServiceFee.ToInt().ToText());
                        serviceFee = tempLogs.Sum(l => l.RepairPrice);
                        excel.SetCellValue(5, 1, serviceFee);

                        //应收合计
                        excel.SetCellValue(6, 1, repariFee + serviceFee);

                        //应退押金
                        decimal? depositFee = 0;
                        tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.ReturnDeposit.ToInt().ToText());
                        depositFee = tempLogs.Sum(l => l.RepairPrice);
                        if (!depositFee.HasValue)
                            depositFee = 0;
                        excel.SetCellValue(7, 1, Math.Abs(depositFee.Value));

                        //处理 实际收款 & 实际退款
                        decimal? actualPay = 0; //实际付款
                        decimal? actualReturn = 0; //实际退款
                        actualPay = repariFee + serviceFee + depositFee;
                        if (actualPay < 0)
                        {
                            actualReturn = Math.Abs(actualPay.Value);
                            actualPay = 0;
                        }
                        excel.SetCellValue(6, 5, actualPay); //写入实际收款
                        excel.SetCellValue(7, 5, actualReturn); //写入实际退款

                        //int index = 0;
                        //var lg = logs.GroupBy(l => l.TransactionType).ToList();
                        //lg.Each(g =>
                        //{
                        //    excel[4 + index, 0] = g.Key + "：";
                        //    excel.SetCellValue(4 + index, 1, g.Sum(l => l.RepairPrice));
                        //    index++;
                        //});

                        //将交易类型以下的行向上移动
                        //excel.ShiftRows(9,17,-(5-lg.Count()));
                        //excel.ShiftRows(7, 15, -(3 - lg.Count()));
                    });
                    */


                    //维修费
                    decimal? repariFee = 0;
                    var tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.RepairObu.ToInt().ToText()
                        || l.TransactionTypeID == TransactionType.IssueBase.ToInt().ToText()
                        || l.TransactionTypeID == TransactionType.IssueSpareTape.ToInt().ToText()
                         || l.TransactionTypeID == TransactionType.OneRepair.ToInt().ToText());
                        //|| l.TransactionTypeID == TransactionType.IssueSpareTape.ToInt().ToText() 
                        //    || l.TransactionTypeID == TransactionType.OneRepair.ToInt().ToText());
                    repariFee = tempLogs.Sum(l => l.RepairPrice);
                    if (repariFee > 0)
                        ViewBag.RepariFee = string.Format("{0} (元)", repariFee);
                    else
                        ViewBag.RepariFee = "0 (元)";

                    //服务费
                    decimal? serviceFee = 0;
                    tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.RepairServiceFee.ToInt().ToText());
                    serviceFee = tempLogs.Sum(l => l.RepairPrice);
                    if (serviceFee > 0)
                        ViewBag.ServiceFee = string.Format("{0} (元)", serviceFee);
                    else
                        ViewBag.ServiceFee = "0 (元)";

                    //应收合计
                    decimal? repairAndServiceFee = repariFee + serviceFee;
                    if (repairAndServiceFee > 0)
                        ViewBag.RepairAndServiceFee = string.Format("{0} (元)", repairAndServiceFee);
                    else
                        ViewBag.RepairAndServiceFee = "0 (元)";

                    //应退押金
                    decimal? depositFee = 0;
                    tempLogs = logs.Where(l => l.TransactionTypeID == TransactionType.ReturnDeposit.ToInt().ToText());
                    depositFee = tempLogs.Sum(l => l.RepairPrice);
                    if (!depositFee.HasValue)
                        depositFee = 0;
                    ViewBag.DepositFee = String.Format("{0} (元)", Math.Abs(depositFee.Value));


                    //处理 实际收款 & 实际退款 

                    decimal? actualPay = 0; //实际付款
                    decimal? actualReturn = 0; //实际退款
                    decimal? fundYajin = 0; //资金来源为押金转的金额

                    //查询整个流水单的资金来源
                    var fundDetailInfo = (from i in db.FUND_DETAIL.ToList()
                                          where i.SERIAL_ID == log.SERIAL_ID
                                          select i).ToList();
                    var fundInfo = new List<FUND_INFO>();
                    if (fundDetailInfo != null && fundDetailInfo.Count() > 0)
                    {
                        var longIDs = from id in fundDetailInfo
                                      select id.FUND_ID;

                        fundInfo = (from i in db.FUND_INFO.ToList()
                                    where longIDs.Contains(i.ID)
                                    select i).ToList();
                    }


                    if (fundInfo != null && fundInfo.Count() > 0)
                    {
                        fundInfo.Each(f =>
                        {
                            switch (f.FUND_FROM)
                            {
                                case 10:
                                    fundYajin += f.AMOUNT;
                                    break;
                                default:
                                    actualPay += f.AMOUNT;
                                    break;//如有还有别的资金项 则累实收金额
                            }
                        });
                        actualReturn = (depositFee) * (-1) - fundYajin;//实退金额为押金退费减去押金转后的
                    }
                    else
                    {

                        actualPay = repariFee + serviceFee + depositFee;
                        if (actualPay < 0)
                        {
                            actualReturn = Math.Abs(actualPay.Value);
                            actualPay = 0;
                        }
                    }
                    ViewBag.ActualPay = String.Format("{0} (元)", actualPay);//写入实际收款
                    ViewBag.ActualReturn = String.Format("{0} (元)", actualReturn);//写入实际退款


                    result = View("PrintTransInMoney", log);
                    #endregion
                }

                //result = export.DownLoad(this.File, exportFileTitle);
            }
            catch (Exception ex)
            {
                result = ExportHelper.HandleExportException(this, ex, exportFileTitle);
            }
            return result;
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            obuMgr.Dispose();
            configMgr.Dispose();
            uMgr.Dispose();

        }
        public ActionResult checkIsExistInvoice(string serialID)
        {
            try
            {
                var idArray = serialID.Split(',').Distinct();

                var transactions = db.INVOICE_DETAIL.ToList();

                var longIDs = from id in idArray
                              select id.ToLong().Value;

                var v = (from i in transactions
                         where longIDs.Contains(i.SERIAL_ID)
                         select i).ToList();
                if (v != null && v.Count() > 0)
                {
                    return Json(new { Success = false, ErrorMsg = "该流水单已开具发票，无法再次进行录入！" });
                }
                return Json(new { Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                string Message = "错误：无法进行发票录入，请从发票管理进入！";
                return Json(new { Success = false, ErrorMsg = Message });
            }
        }
    }
}
